package fy.mdm.dao;

import java.io.IOException;
//import java.io.InputStream;
import java.nio.charset.Charset;





import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.apache.commons.io.IOUtils;
/*import org.apache.commons.lang.ObjectUtils;*/
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
//import org.apache.http.client.methods.HttpPut;
//import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.entity.StringEntity;
//import org.apache.http.entity.ByteArrayEntity;
//import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;



import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

//import java.util.Properties;





import javax.crypto.Cipher;

import java.io.*;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
//import java.io.IOException;
import java.util.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

//import net.sf.json.JSONObject;
class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception {
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

public class EnclosureService {
	private static Log log = LogFactory.getLog(EnclosureService.class);
	
	 static final String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7JL0DcaMUHumSdhxXTxqiABBC\n" +
	            "DERhRJIsAPB++zx1INgSEKPGbexDt1ojcNAc0fI+G/yTuQcgH1EW8posgUni0mcT\n" +
	            "E6CnjkVbv8ILgCuhy+4eu+2lApDwQPD9Tr6J8k21Ruu2sWV5Z1VRuQFqGm/c5vaT\n" +
	            "OQE5VFOIXPVTaa25mQIDAQAB";

    // 鏈嶅姟鍣ㄩ厤缃拰甯愬彿淇℃伅
    private String ip;

    // 淇濆瓨userid鍜宼okenid閴存潈淇℃伅锛岀敤鏉ュ彂閫佸悗缁殑璇锋眰
    private String userid;
    private String tokenid;
	private static String main_data_id;// 编码
	private static String main_data_name;// 描述
	private static String drawingsname;// 图纸名称
	private static String drawings;// 图纸
	private static String drawings_version;//图纸版本
	private static String resultStr;

	public JSONObject getEnclosureService() throws Exception {
		JSONObject jo = new JSONObject();
		JSONObject ja = new JSONObject();
		try {
//			EnclosureService service = new EnclosureService();
			String ip = "192.168.136.45";
	        String account = "user01";
	        String password = "eisoo.com";
	        SetServerIP(ip);
	        //service.LogIn(account, password);
	        
			String url = "http://10.112.5.159:8091/mdmWebService/services/WebServicesClassification?wsdl";
//			http://10.112.5.159:8091/mdmWebService/services/WebServicesClassification?wsdl
			int timeout = 10000;
			StringBuffer sb = new StringBuffer("");
			sb.append(
					"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\"http://com\">");
			sb.append("<soapenv:Header/>");
			sb.append("<soapenv:Body>");
			sb.append("<com:getDrawController>");
			sb.append("<com:main_data_id>"+main_data_id+"</com:main_data_id>");// BS25151G
			sb.append("</com:getDrawController>");
//			sb.append("</soap:Body>");
			sb.append("</soapenv:Body>");
			sb.append("</soapenv:Envelope>");
//			HttpClient client = new HttpClient();
//			PostMethod postMethod = new PostMethod(url);
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);

			RequestConfig requestConfig = RequestConfig.custom()  
			        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
			        .setSocketTimeout(5000).build(); 
			httpPost.setConfig(requestConfig); 
			httpPost.setHeader("Content-Type", "HttpToSoap.soap");
	        httpPost.setHeader("SOAPAction", "");
	        StringEntity data = new StringEntity(sb.toString(), Charset.forName("UTF-8"));
	        System.out.println("data: " + sb.toString());
	        httpPost.setEntity(data);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();//得到请求回来的数据
			String result = EntityUtils.toString(entity, "UTF-8");
			System.out.println("result: " + result);
			Document dom = DocumentHelper.parseText(result);
			System.out.println("dom: " + dom);
			Element root = dom.getRootElement();
			List<Element> childNodes = root.elements();
			System.out.println("childNodes: " + childNodes.size());
			// JSONObject classInfo = new JSONObject();
			dom4jList(root);
			JSONObject jsStr = JSONObject.parseObject(resultStr);
//			JSONObject jsStr = JSONObject.fromObject(resultStr);
			JSONArray  attlist =jsStr.getJSONArray("attlist");
			JSONObject osdownload = attlist.getJSONObject(0);
			drawings = osdownload.getString("outsidelink");
			drawings.replaceAll("(.*)#/(.*)", "");
			String drawing=drawings.replaceAll("(.*)#/(.*)", "");
			System.err.println(drawing);
			//表单参数
			main_data_name = jsStr.getString("MATERIEL_DESCRIBE");
			drawingsname = osdownload.getString("ATTACHMENT_NAME");
			drawings_version = osdownload.getString("VERSION");
			log.info("main_data_name:"+main_data_name+"drawings:"+drawingsname+"drawings_version:"+drawings_version);
			log.info(drawings);
			jo.put("main_data_name", main_data_name);
			jo.put("drawingsname", drawingsname);
			jo.put("drawings_version", drawings_version);
			jo.put("drawings", drawings);
			log.info(jo);
			ja.put("main_data_id"+main_data_id,jo);

//			String downurl = (String) authrequest.get(1);
//	        String date = ((String) authrequest.get(2)).substring(12);
//	        String length = ((String) authrequest.get(3)).substring(14);
//	        String auth = ((String) authrequest.get(4)).substring(14);
	        //下载
//	        DownloadGet(downurl, date, length, auth, "C:\\Users\\GNB543\\Desktop\\formLogo.png");//修改路径
	   //     C:\Users\GNB543\Desktop

		} catch (Exception e) {
			// TODO: handle exception
		}
		log.info(ja);
		return ja;
	}



	public void dom4jList(Element element) { // 遍历XML文件
		//String result = "";
		// 获取文件中父元素的名称和文本内容
//		System.out.println("getTextTrim:" + element.getTextTrim());
		if (!element.getTextTrim().equals("")) {
//			System.out.println(element.getTextTrim());
			this.resultStr = element.getTextTrim();

		}
		// 创建迭代器对象判断该父元素是否还有子元素，有的话，就获取子元素的名称和文本内容
		Iterator iterator = element.elementIterator();
		while (iterator.hasNext()) {
			Element e = (Element) iterator.next();
			// 递归调用自身方法判断该子元素是否还存在子元素，以此类推并获取信息
			dom4jList(e);
		}
		// System.out.println("-------");

	}
	public void SetServerIP(String ip) {
        this.ip = ip;
    }
	public static String RSAEncode(String pass) throws IOException, GeneralSecurityException {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(pubKey)));

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return new BASE64Encoder().encode(cipher.doFinal(pass.getBytes("UTF-8"))).replace("\r\n", "\n");
    }
    
    public JSONObject Osdownload(String gns, String savepath) throws Exception {
        // 鎺ュ彛鏍煎紡锛堝寘鍚玌RL璇锋眰鏍煎紡銆佸弬鏁拌鏄庡強璇锋眰绀轰緥锛夎鍙傝銆�2-AnyShare5.0鏂囨。璁块棶寮�鏀続PI鎺ュ彛鏂囨。 - 瀵瑰.docx銆� 4.4 鑺�
        String url = "http://" + this.ip + ":9123/v1/file?method=osdownload&userid=" + this.userid + "&tokenid=" + this.tokenid;
        //uploadjson = {'docid' : gns, 'length' : length, 'name':name, 'client_mtime':clienttime, 'ondup':ondup}
        JSONObject dir = new JSONObject();
        dir.put("docid", gns);
        //dir.put("md5", name);
        //dir.put("clienttime", clienttime);
        //dir.put("ondup", 2);
        String strdir = dir.toString();

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost methodd = new HttpPost(url);
        StringEntity se = new StringEntity(strdir, "UTF-8");
        methodd.setEntity(se);

        CloseableHttpResponse response = client.execute(methodd);
        HttpEntity entity = response.getEntity();
        String strResult = EntityUtils.toString(entity);
        JSONObject retunjson = JSONObject.parseObject(strResult);
        methodd.releaseConnection();

        System.out.println("Osdownload: " + strResult);
        String downurl = (String) retunjson.getJSONArray("authrequest").get(1);
        String date = ((String) retunjson.getJSONArray("authrequest").get(2)).substring(12);
        String length = ((String) retunjson.getJSONArray("authrequest").get(3)).substring(14);
        String auth = ((String) retunjson.getJSONArray("authrequest").get(4)).substring(14);
        DownloadGet(downurl, date, length, auth, savepath);
        return retunjson;
    }
    public static String DownloadGet(String url, String date, String length, String auth, String savepath) throws Exception {
    	try {
    		HttpClient client = null;
            client = new SSLClient();
            System.out.println("url:"+url);	
            HttpGet methodd = new HttpGet(url);
            methodd.addHeader("X-Eoss-Date", date);
            methodd.addHeader("X-Eoss-Length", length);
            methodd.addHeader("Authorization", auth);
            HttpResponse response = client.execute(methodd);
            HttpEntity ba = response.getEntity();
            System.out.println("ba:"+ba);
            File mysavepath = new File(savepath);
            mysavepath.createNewFile();
            FileOutputStream out = new FileOutputStream(mysavepath, false);
            out.write(EntityUtils.toByteArray(ba));
            out.close();
            HttpEntity entity = response.getEntity();
            methodd.releaseConnection();
            System.out.println("download path:" + savepath);
            
    	}catch(Exception e){e.printStackTrace();}
    	return "download path:" + savepath;
    }
    public String getInfoByPath(String namepath) throws Exception {
        String url = "http://" + this.ip + ":9123/v1/file?method=getinfobypath&userid=" + this.userid + "&tokenid=" + this.tokenid;
        JSONObject reqbody = new JSONObject();
        reqbody.put("namepath",  namepath);
        String reqstr =reqbody.toString();
        System.out.println("reques json: " + reqstr);

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost methodd = new HttpPost(url);
        System.out.println("reques url: " + url);
        StringEntity se = new StringEntity(reqstr, "UTF-8");
        methodd.setEntity(se);

        CloseableHttpResponse response = client.execute(methodd);
        HttpEntity entity = response.getEntity();
        String strResult = EntityUtils.toString(entity);
        JSONObject retunjson = JSONObject.parseObject(strResult);
        methodd.releaseConnection();

        System.out.println("getinfobypath: " + strResult);
        return retunjson.getString("docid");
    }
	public static String getMain_data_id() {
		return main_data_id;
	}

	public static void setMain_data_id(String main_data_id) {
		EnclosureService.main_data_id = main_data_id;
	}
}